package org.freemarker.web.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.freemarker.core.model.Contact;
import org.freemarker.core.service.CarService;
import org.freemarker.core.service.impl.ContactServiceImpl;
import org.freemarker.web.custom.CustomHttpServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;


@Controller
public class ContactDeleteController extends CustomHttpServlet {

	private static final long serialVersionUID = -3661440629229458127L;
	private static final Logger logger = LoggerFactory
			.getLogger(ContactServiceImpl.class);
	@Autowired
	CarService carService;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		req.getRequestDispatcher("views/contact/delete.ftl").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String securityNumber = req.getParameter("securityNumber");
		
		
		Contact c= new Contact();
		try {
			c = contactService.getContactBySecurityNumber(securityNumber);
		} catch (Exception e1) {
			String updtError;
			updtError="Contact not found in database!";
			List<Contact> users = contactService.findAll();
			req.setAttribute("users", users);
			req.setAttribute("updtError",updtError);
			req.getRequestDispatcher("views/contact/list.ftl").forward(req, resp);
		}
		try {
			carService.deleteById(carService.getCarForContact(c.getId()).getId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		contactService.deleteById(c.getId());
		
		List<Contact> users = contactService.findAll();
		req.setAttribute("users", users);
		req.getRequestDispatcher("views/contact/list.ftl").forward(req, resp);
	/*
		List<Car> cars =carService.findAll();
		req.setAttribute("cars",cars);
		req.getRequestDispatcher("views/car/listCars.ftl").forward(req,resp);*/
	
	}
}
